// 获取合并的数据
export const mergeConfig = (that, data) => {
	// 判断url是不是链接that
	let urlType = /^(http|https):\/\//.test(data.url);
	// Object.assign(目标对象, 源对象)  将源对象合并到目标对象中，
	// 如果出现相同key，采用源对象的key覆盖目标对象
	let config = Object.assign({ timeout: that.timeout }, that.config, data)
	
	if(data.method === 'FILE') {
		config.url = urlType ? data.url : that.fileUrl + data.url;
	} else {
    config.url = urlType ? data.url : that.baseUrl + data.url;
  }
  // 请求头 data.header请求参数中是否携带有请求头信息配置,有合并
  if(data.header) {
    config.header = Object.assign({}, that.header, data.header);
  } else {
    config.header = Object.assign({}, that.header)
  }
  return config
}

// 开始发送请求
export const dispatchRequest = (requestInfo)=> {
	return new Promise((resolve, reject) => {
		let requestAbort = true;
		let requestData = {
			url: requestInfo.url,
			header: requestInfo.header,
			success: (res) => {
				requestAbort = false;
				resolve(res);
			},
			fail: (err) => {
				requestAbort = false;
				if(err.errMsg == 'request:fail about') {
					reject({
						errMsg: '请求超时，请重新尝试',
						statusCode: 0
					})
				} else {
					reject(err)
				}
			}
		}
		// 请求类型
		if(requestInfo.method) {
			requestData.method = requestInfo.method;
		}
		// 请求体
		if(requestInfo.data) {
			requestData.data = requestInfo.data;
		}
		// #ifdef MP-WEIXIN || MP-MP-ALIPAY
		if(requestInfo.timeout) {
			requestData.timeout = requestInfo.timeout;
		}
		// #endif
		
		if (requestInfo.dataType) {
		  requestData.dataType = requestInfo.dataType;
		}
		
		// #ifndef APP-PLUS || MP-ALIPAY
		if (requestInfo.responseType) {
		  requestData.responseType = requestInfo.responseType;
		}
		// #endif
		
		// #ifdef H5
		if (requestInfo.withCredentials) {
		  requestData.withCredentials = requestInfo.withCredentials;
		}
		// #endif
		
		// 执行网络请求
		let requestTask = uni.request(requestData);
		// 请求超时处理：终止发送网络请求
		setTimeout(() => {
			if(requestAbort) {
				requestAbort.abort();
			}
		}, requestInfo.timeout)
	})
}

// jsonp请求
export const jsonpRequest = (requestInfo) => {
  return new Promise((resolve, reject) => {
    let dataStr = '';
    Object.keys(requestInfo.data).forEach(key => {
      dataStr += key + '=' + requestInfo.data[key] + '&';
    });
    //匹配最后一个&并去除
    if (dataStr !== '') {
      dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
    }
    requestInfo.url = requestInfo.url + '?' + dataStr;
    let callbackName = "callback" + Math.ceil(Math.random() * 1000000);
    // #ifdef H5
    window[callbackName] = (data) => {
      resolve(data);
    }
    let script = document.createElement("script");
    script.src = requestInfo.url + "&callback=" + callbackName;
    document.head.appendChild(script);
    // 及时删除，防止加载过多的JS
    document.head.removeChild(script);
    // #endif
  });
}
